import openpyxl
import requests
import time
import json

def get_bearer_token():
    # 从authToken.txt文件中读取bearer_token的值
    with open("file/authToken.txt", "r") as file:
        return file.read().strip()


def read_excel(file_path):
    wb = openpyxl.load_workbook(file_path)
    sheet = wb.active
    data = []

    for row in sheet.iter_rows(min_row=2, values_only=True):
        blood_code = row[2]
        phone_number = row[3]
        data.append((blood_code, phone_number))

    return data

def call_api(alias, token, blood_code, phone_number):
    url = f"http://api.17donor.com/right/admin/{alias}/donorSubsidy/records/with-serial"
    headers = {"Authorization": f"Bearer {token}"}
    payload = {
        "phone": phone_number,
        "awardIds": [31],
        "donationSerial": blood_code
    }

    try:
        response = requests.post(url, json=payload, headers=headers)
        print(response.json())
        response.raise_for_status()  # 如果响应状态码不是200，会抛出异常
        
        if(response.json().get("status") == 200):
            print("派发成功-"+blood_code)
            return "派发成功", "派发成功", "派发成功"
        else:
            error_message = response.json().get("message", "未知错误")
            print(f"派发失败 code: {blood_code}, msg: {error_message}")
            return error_message, "派发失败", response.json()

    except Exception as e:
        print(f"派发异常 e: {str(e)}")
        return str(e), "派发异常", '派发异常'

def update_excel(file_path, results):
    wb = openpyxl.load_workbook(file_path)
    sheet = wb.active

    for index, (blood_code, result, message, response_json) in enumerate(results, start=2):
        sheet.cell(row=index, column=9, value=result)
        if message:
            sheet.cell(row=index, column=10, value=message)
        if response_json:
            json_string = json.dumps(response_json, ensure_ascii=False, indent=2)
            sheet.cell(row=index, column=11, value=json_string)

    wb.save(file_path)

def main():
    file_path = "file/南宁待派发清单-test.xlsx"
    alias = "nanning"
    data = read_excel(file_path)    
    print(f"读取文件成功")
    
    # 获取数据
    results = []
    for blood_code, phone_number in data:
        message, result, response_json = call_api(alias, get_bearer_token(), blood_code, phone_number)
        results.append((blood_code, result, message, response_json))
        time.sleep(0.2)  # 间隔500ms
    
    # 写入excel
    update_excel(file_path, results)

if __name__ == "__main__":
    main()
